package tcards.android;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import models.AircraftTcard;
import models.HandCrewTcard;
import models.HelicopterTcard;
import models.Kind;
import models.PersonnelTcard;
import models.ResourceTcard;
import models.Status;
import models.Tcard;
import models.UpdateHistory;
import util.StringUtil;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

public class EditPage extends LinearLayout {
	private TextDisplay  mKindDisplay;
	private TextDisplay  mStatusDisplay;
	private TextDisplay  mDatePrepared;
	private TextField    mPreparedBy;
	private ScrollView   mCardEdit;
	private LinearLayout mChangeLog;
	
	private GeneralFieldList mGeneralList;
	
	private Tcard mTcard;
	private boolean mIsUpdate;
	private boolean mDeletePressed;
	
	private void init(Tcard tcard) {
		mKindDisplay.getContent().setText(tcard.getKind().toDisplayString());
		mKindDisplay.getContent().setTextColor(TcardButton.getColorForKind(tcard.getKind()));
		mStatusDisplay.getContent().setText(tcard.getStatus().toDisplayString());		
		
		switch(tcard.getKind()) {
		case HandCrews:
			CrewFieldList cfl = new CrewFieldList(getContext());
			cfl.setListFields((HandCrewTcard) tcard);
			mGeneralList = cfl.getGeneralList();
			mCardEdit.addView(cfl);
			break;
		case Personnel:
			PersFieldList pfl = new PersFieldList(getContext());
			pfl.setListFields((PersonnelTcard) tcard);
			mGeneralList = pfl.getGeneralList();
			mCardEdit.addView(pfl);
			break;
		case Helicopters:
			HeliFieldList hfl = new HeliFieldList(getContext());
			hfl.setListFields((HelicopterTcard) tcard);
			mGeneralList = hfl.getGeneralList();
			mCardEdit.addView(hfl);
			break;
		case Aircraft:
			AirFieldList afl = new AirFieldList(getContext());
			afl.setListFields((AircraftTcard) tcard);
			mGeneralList = afl.getGeneralList();
			mCardEdit.addView(afl);
			break;
		default:
			ResourceFieldList rfl = new ResourceFieldList(getContext());
			rfl.setListFields((ResourceTcard) tcard);
			mGeneralList = rfl.getGeneralList();
			mCardEdit.addView(rfl);
		}
		
		mPreparedBy.setTextValue(tcard.getAuthor());
	}
	
	//New T-Card
	public EditPage(Context context, Kind kind, Status status) {
		this(context, null, 0);		
		mTcard = Tcard.createCard(kind, status);
		mIsUpdate = false;
		mDeletePressed = false;
		
		Format dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mma");
		String currentDate = dateFormat.format(new Date());
		mDatePrepared.getContent().setText(currentDate);
		
		UpdateEntry entry = new UpdateEntry(context);
		entry.getDate().getContent().setText(currentDate);
		entry.getOldStatus().getContent().setText(status.toDisplayString());
		entry.getNewStatus().getContent().setText(status.toDisplayString());
		setDeleteListener(entry);
		UpdateHistory history = new UpdateHistory(status, status);
		entry.setHistoryFields(history);
		mTcard.getHistory().add(history);
		mChangeLog.addView(entry);
		
		
		init(mTcard);
	}
	
	//Existing T-Card
	public EditPage(Context context, Tcard tcard) {
		this(context, null, 0);		
		mTcard = tcard;
		mIsUpdate = true;
		mDeletePressed = false;
		
		Format dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mma");
		mDatePrepared.getContent().setText(dateFormat.format(tcard.getCreated()));
		
		for (int i = tcard.getHistory().size() - 1; i >= 0; --i) {
			UpdateEntry entry = new UpdateEntry(context);
			entry.setListFields(tcard.getHistory().get(i));
			setDeleteListener(entry);
			mChangeLog.addView(entry);
		}
		
		init(mTcard);
	}

	public EditPage(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater li = LayoutInflater.from(context);
		addView(li.inflate(R.layout.edit_page, this, false));
		
		mKindDisplay   = (TextDisplay)  findViewById(R.id.kindDisplay);
		mStatusDisplay = (TextDisplay)  findViewById(R.id.statusDisplay);
		mDatePrepared  = (TextDisplay)  findViewById(R.id.datePreparedDisplay);
		mPreparedBy    = (TextField)    findViewById(R.id.preparedByField);
		mCardEdit      = (ScrollView)   findViewById(R.id.cardEdit);
		mChangeLog     = (LinearLayout) findViewById(R.id.changeLog);
	}
	
	private void setDeleteListener(UpdateEntry entry) {
		entry.setDeleteOnClick(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mDeletePressed) {
		    		mDeletePressed = false;
		    		UpdateEntry entry = (UpdateEntry) v.getParent().getParent().getParent();
		    		mTcard.getHistory().remove(reverseIndex(getEntryIndex(entry)));
		    		mChangeLog.removeView(entry);
		    	}
				else {
		    		mDeletePressed = true;
					Toast.makeText(getContext(), "Press the delete button again to confirm", Toast.LENGTH_LONG).show();
					TimerTask task = new TimerTask() {
						public void run() {
							mDeletePressed = false;
						}
					};
					Timer t = new Timer("Entry Delete Button Reset");
					t.schedule(task, 4000); // user has 4 seconds to push delete again
			    }
			}			
		});
		
		entry.setDeleteOnLongClick(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				UpdateEntry entry = (UpdateEntry) v.getParent().getParent().getParent();
	    		mTcard.getHistory().remove(reverseIndex(getEntryIndex(entry)));
	    		mChangeLog.removeView(entry);
				return true;
			}		
		});
	}
	
	public String validate()
	{
		String errors = "";
		
		if (StringUtil.IsNullOrEmpty(mPreparedBy.getTextValue())) {
			errors += "Prepared by is a required field\n";
		}
		if (StringUtil.IsNullOrEmpty(mGeneralList.getSTUnit().getTextValue())) {
			errors += "ST/Unit is a required field\n";
		}
		if (StringUtil.IsNullOrEmpty(mGeneralList.getName().getTextValue())) {
			errors += "Name/ID # is a required field\n";
		}
		
		return errors;
	}
	
	public Tcard getTcard()
	{
		switch(mTcard.getKind()) {
		case HandCrews:
			CrewFieldList cfl = (CrewFieldList) mCardEdit.getChildAt(0);
			cfl.setTcardFields((HandCrewTcard) mTcard);
			break;
		case Personnel:
			PersFieldList pfl = (PersFieldList) mCardEdit.getChildAt(0);
			pfl.setTcardFields((PersonnelTcard) mTcard);
			break;
		case Helicopters:
			HeliFieldList hfl = (HeliFieldList) mCardEdit.getChildAt(0);
			hfl.setTcardFields((HelicopterTcard) mTcard);
			break;
		case Aircraft:
			AirFieldList afl = (AirFieldList) mCardEdit.getChildAt(0);
			afl.setTcardFields((AircraftTcard) mTcard);
			break;
		default:
			ResourceFieldList rfl = (ResourceFieldList) mCardEdit.getChildAt(0);
			rfl.setTcardFields((ResourceTcard) mTcard);
		}
		
		mTcard.setAuthor(mPreparedBy.getTextValue());
		
		for (int i = mChangeLog.getChildCount() - 1; i >= 0; --i) {
			UpdateEntry entry = (UpdateEntry) mChangeLog.getChildAt(i);
			entry.setHistoryFields(mTcard.getHistory().get(reverseIndex(i)));
		}
		
		return mTcard;
	}
	
	public boolean isUpdate() {
		return mIsUpdate;
	}
	
	public TextField getPreparedBy() {
		return mPreparedBy;
	}
	
	private int reverseIndex(int i) {
		return mTcard.getHistory().size() - 1 - i;
	}
	
	public int getEntryIndex(UpdateEntry entry) {
		for (int i = 0; i < mChangeLog.getChildCount(); ++i) {
			if (mChangeLog.getChildAt(i) == entry) {
				return i;
			}
		}
		return -1;
	}
}
